package com.quwan.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.quwan.app.service.ProductCategoryService;
import com.quwan.common.enums.CommonStatus;
import com.quwan.common.result.PageResult;
import com.quwan.config.yml.OssConfig;
import com.quwan.constans.CacheKey;
import com.quwan.entity.TProductCategory;
import com.quwan.mapper.TProductCategoryMapper;
import com.quwan.utils.DateUtils;
import com.quwan.utils.Parse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author quan
 * @date 2021-06-09 14:53
 */

@Service
@RequiredArgsConstructor
public class ProductCategoryServiceImpl implements ProductCategoryService {
    private final TProductCategoryMapper productCategoryMapper;
    private final OssConfig ossConfig;

    @Override
    public List<TProductCategory> getAppIndexOwner() {
        return productCategoryMapper
                .selectAll()
                .stream()
                .filter(f -> f.getStatus() == 1)
                .map(m -> StringUtils.isBlank(m.getIcon()) ? m : m.setIcon(ossConfig.getHostname() + "/" + m.getIcon()))
                .collect(Collectors.toList());
    /*    Map<Integer, List<TProductCategory>> groupByOwner =
                productCategoryMapper.selectAll()
                        .stream()
                        .filter(f -> f.getCateType() != null)
                        .collect(Collectors.groupingBy(TProductCategory::getCateType));
        //owner 0 代表顶级分类
        return groupByOwner.entrySet()
                .stream()
                .map(parent -> {
                            ParentCatesEnum type = ParentCatesEnum.getByType(parent.getKey());
                            if (type == null) return null;
                            return new ParentCatesDTO()
                                    .setCaption(type.getCaption())
                                    .setRemarks(type.getTips())
                                    .setItems(parent.getValue()
                                            .stream()
                                            .map(i -> i.setIcon(StringUtils.isBlank(i.getIcon()) ? null : ossConfig.getHostname() + "/" + i.getIcon()))
                                            .collect(Collectors.toList()));
                        }
                )
                .collect(Collectors.toList());
*/
    }

    @Override
    public List<TProductCategory> getAppIndexOwnerNew() {
        List<TProductCategory> categoryList = productCategoryMapper.selectAll();
        categoryList.stream().filter(c->c.getStatus().equals(CommonStatus.NORMAL.getType())).forEach(item->{
            if (StringUtils.isNotBlank(item.getIcon()))
                item.setIcon(ossConfig.getHostname()+"/"+item.getIcon());
            if (StringUtils.isNotBlank(item.getBgImg()))
                item.setBgImg(ossConfig.getHostname() + "/" + item.getBgImg());
        });
        Map<Long, List<TProductCategory>> group = categoryList.stream().filter(c->c.getStatus().equals(CommonStatus.NORMAL.getType())).collect(Collectors.groupingBy(TProductCategory::getOwner));
        List<TProductCategory> parent = group.get(0L);
        List<TProductCategory> recommend = categoryList
                .stream()
                .filter(cate -> !"0".equals(cate.getParentId()) && cate.getShowIndex() == 1&&cate.getStatus().equals(CommonStatus.NORMAL.getType())).collect(Collectors.toList());

        parent.forEach(item->
            item.setChild(group.get(item.getId()))
        );
     parent.add( new TProductCategory().setOrderNum(-1).setCaption("推荐").setChild(recommend));
        return parent.stream().sorted(Comparator.comparing(TProductCategory::getOrderNum)).collect(Collectors.toList());

    }

    @Override
    public TProductCategory getProductCategoryById(Long categoryId) {
        TProductCategory res = productCategoryMapper.selectById(categoryId);
        if (res != null) {
            if (StringUtils.isNotBlank(res.getIcon()))
                res.setIcon(ossConfig.getHostname() + "/" + res.getIcon());
            if (StringUtils.isNotBlank(res.getBgImg()))
                res.setBgImg(ossConfig.getHostname() + "/" + res.getBgImg());
        }
        return res;
    }

    @Override
    public PageResult<TProductCategory> getAllCateTag(int page, int size, String id, String caption, Integer cateType, String beginTime, String endTime) {
        LocalDate begin = null;
        LocalDate end = null;
        if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
            begin = LocalDate.parse(beginTime.trim());
            end = LocalDate.parse(endTime.trim());
        }
        String hostName = ossConfig.getHostname();
        Page<Map<String, Object>> res =
                productCategoryMapper
                        .selectCateTagList(
                                new Page<>(page, size), id, caption, cateType, begin, end);

        List<TProductCategory> result =
                res
                        .getRecords()
                        .stream()
                        .map(m -> {
                            Map<String, String> map = Maps.transformEntries(m, (k, v) -> String.valueOf(v));

                            return new TProductCategory()
                                    .setAddBy(map.get("add_by"))
                                    .setAddTime(DateUtils.str2Date(map.get("add_time")))
                                    .setShowIndex(Integer.parseInt(map.get("show_index")))
                                    .setParentName(map.get("parentName"))
                                    .setId(Long.parseLong(map.get("id")))
                                    .setIcon(StringUtils.isBlank(map.get("icon")) ? "" : ossConfig.getHostname() + "/" + map.get("icon"))
                                    .setBgImg(StringUtils.isBlank(map.get("bg_img")) ? "" : ossConfig.getHostname() + "/" + map.get("bg_img"))
                                    .setCaption(map.get("caption"))
                                    .setParentId(map.get("parentId"))
                                    .setOwner(Parse.toLong(map.get("owner"),0L))
                                    .setCateType(StringUtils.isBlank(map.get("cate_type")) ? null : Integer.parseInt(map.get("cate_type")))
                                    .setRemarks(map.get("remarks"))
                                    .setOrderNum(StringUtils.isBlank(map.get("order_num")) ? null : Integer.valueOf(map.get("order_num")));
                        })
                        .collect(Collectors.toList());

        return new PageResult<TProductCategory>()
                .setRecords(result)
                .setCurrent(res.getCurrent())
                .setSize(res.getSize())
                .setPages(res.getPages())
                .setTotal(res.getTotal());
    }

    @CacheEvict(cacheNames = CacheKey.DATA.cates, allEntries = true)
    @Override
    public boolean updCateTag(TProductCategory category) {
        return productCategoryMapper
                .update(null,
                        new LambdaUpdateWrapper<TProductCategory>()
                                .set(StringUtils.isNotBlank(category.getIcon()), TProductCategory::getIcon, category.getIcon())
                                .set(StringUtils.isNotBlank(category.getCaption()), TProductCategory::getCaption, category.getCaption())
                                .set(StringUtils.isNotBlank(category.getRemarks()), TProductCategory::getRemarks, category.getRemarks())
                                .set(category.getShowIndex()!=null, TProductCategory::getShowIndex, category.getShowIndex())
                                .set(TProductCategory::getOwner,category.getOwner()==null?0:category.getOwner())
                                .set(category.getOrderNum()!=null,TProductCategory::getOrderNum,category.getOrderNum())
                                .set(StringUtils.isNotBlank(category.getBgImg()),TProductCategory::getBgImg,category.getBgImg())
                                .eq(TProductCategory::getId, category.getId())

                    ) == 1;
    }

    @CacheEvict(cacheNames = CacheKey.DATA.cates, allEntries = true)
    @Override
    public boolean addCateTag(TProductCategory category) {
        return productCategoryMapper.insert(category) == 1;
    }

    @CacheEvict(cacheNames = CacheKey.DATA.cates, allEntries = true)
    @Override
    public boolean delCateTag(Long id) {
        return productCategoryMapper.updateById(new TProductCategory().setId(id).setStatus(0)) == 1;
    }

    @Override
    public List<TProductCategory> getParentTag() {
        return productCategoryMapper
                .selectList(
                        new QueryWrapper<>(
                                new TProductCategory().setOwner(0L).setStatus(CommonStatus.NORMAL.getType())));
    }


}
